package com.wefans.wefansapp.activity;

import java.text.SimpleDateFormat;
import java.util.Hashtable;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.google.gson.Gson;
import com.sina.weibo.sdk.auth.Oauth2AccessToken;
import com.sina.weibo.sdk.auth.WeiboAuth;
import com.sina.weibo.sdk.auth.WeiboAuthListener;
import com.sina.weibo.sdk.exception.WeiboException;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.wefans.wefansapp.R;
import com.wefans.wefansapp.common.tool.data.MFDataManager;
import com.wefans.wefansapp.common.tool.data.ReqFindAllIdData;
import com.wefans.wefansapp.common.tool.data.ReqLoginData;
import com.wefans.wefansapp.common.tool.data.ReqSnsLoginData;
import com.wefans.wefansapp.common.tool.data.ReqTempPasswordData;
import com.wefans.wefansapp.common.tool.data.ResDefaultData;
import com.wefans.wefansapp.common.tool.data.ResFindIdData;
import com.wefans.wefansapp.common.tool.data.ResLoginData;
import com.wefans.wefansapp.common.tool.debug.MFDebug;
import com.wefans.wefansapp.common.tool.network.MFNetworkManager;
import com.wefans.wefansapp.common.tool.network.MFNetworkManager.IOnNetworkListener;
import com.wefans.wefansapp.common.tool.network.model.NetJsonData;
import com.wefans.wefansapp.common.tool.network.model.NetMessage;
import com.wefans.wefansapp.common.tool.popup.FindAllIdDialog;
import com.wefans.wefansapp.common.tool.popup.FindAllIdDialog.OnFindAllIdListener;
import com.wefans.wefansapp.common.tool.popup.FindIdDialog;
import com.wefans.wefansapp.common.tool.popup.FindIdDialog.OnFindIdListener;
import com.wefans.wefansapp.common.tool.popup.FindPartIdDialog;
import com.wefans.wefansapp.common.tool.popup.FindPartIdDialog.OnFindPartIdListener;
import com.wefans.wefansapp.common.tool.popup.FindPasswordDialog;
import com.wefans.wefansapp.common.tool.popup.FindPasswordDialog.OnFindPasswordListener;
import com.wefans.wefansapp.common.tool.popup.LoginDialog;
import com.wefans.wefansapp.common.tool.popup.LoginDialog.OnLoginListener;
import com.wefans.wefansapp.common.tool.popup.SendPasswordDialog;
import com.wefans.wefansapp.common.tool.preference.MFSharedPreference;
import com.wefans.wefansapp.common.tool.utils.MFToastUtil;

public class LoginActivity extends BaseActivity {   
	
	private final static String LOGIN_NORMAN = "N";
	private final static String LOGIN_WEIBO = "W";
	private final static String LOGIN_WECHAT = "C";
    
	private MFSharedPreference mPrf = null;
	
	private Context mContext = null;
	private LinearLayout mLlGlobalLogin = null;
	private ImageButton mBtnFacebook = null;
	private ImageButton mBtnTwiter = null;
	private LinearLayout mLlChinaLogin = null;
	private ImageButton mBtnWeibo = null;
	private ImageButton mBtnWechat = null;
	private Button mBtnJoin = null;
	private Button mBtnLogin = null;
	
	private boolean bAutoLogin = false;
	private boolean bChina = true;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		
		mContext = this;
		
		mPrf = new MFSharedPreference(getApplicationContext());
		
		String strMemId = mPrf.getMem_idx();
		if (strMemId != null && strMemId.length() > 0) {
			MFDataManager.getInstance(getApplicationContext()).setMemberIdx(strMemId);
			Intent intent = new Intent(LoginActivity.this, MainActivity.class);
			startActivity(intent);
			finish();
		} else {
			setContentView(R.layout.activity_login);
			
			mLlGlobalLogin = (LinearLayout)findViewById(R.id.LL_GLOBAL_LOGIN);
			mBtnFacebook = (ImageButton) findViewById(R.id.BTN_FACEBOOK);
			mBtnTwiter = (ImageButton) findViewById(R.id.BTN_TWITER);
			mLlChinaLogin = (LinearLayout)findViewById(R.id.LL_CHINA_LOGIN);
			mBtnWeibo = (ImageButton) findViewById(R.id.BTN_WEIBO);
			mBtnWechat = (ImageButton) findViewById(R.id.BTN_WECHAT);
			mBtnJoin = (Button) findViewById(R.id.BTN_JOIN);
			mBtnLogin = (Button) findViewById(R.id.BTN_LOGIN);
			
			mBtnFacebook.setOnClickListener(mClickListener);
			mBtnTwiter.setOnClickListener(mClickListener);
			mBtnWeibo.setOnClickListener(mClickListener);
			mBtnWechat.setOnClickListener(mClickListener);
			mBtnJoin.setOnClickListener(mClickListener);
			mBtnLogin.setOnClickListener(mClickListener);
			
			mLlGlobalLogin.setVisibility(bChina ? View.GONE : View.VISIBLE);
			mLlChinaLogin.setVisibility(bChina ? View.VISIBLE : View.GONE);
		}
	}
	
	OnClickListener mClickListener = new OnClickListener() {
		
		Intent intent = null;
		
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.BTN_FACEBOOK:
				break;
			case R.id.BTN_TWITER:
				break;
			case R.id.BTN_WEIBO:
				loginWeibo();
				break;
			case R.id.BTN_WECHAT:
				loginWechat();
			    //startActivity(new Intent(LoginActivity.this, MainActivity.class));
			    //finish();
				break;
			case R.id.BTN_JOIN:
				intent = new Intent(LoginActivity.this, JoinActivity.class);
				startActivity(intent);
				break;
			case R.id.BTN_LOGIN:
				new LoginDialog(mContext, new OnLoginListener() {
					
					public void onLoginInfo(String strId, String strPassword, boolean bAutoLogin) {
						requestLogin(strId, strPassword, bAutoLogin);
					}
					
					public void onFindPassword() {
						showFindPasswordDialog();
						
					}
					
					public void onFindId() {
						showFindIdDialog();
						
					}
				}).show();
				break;
			}
		}
	};
	
	private void requestSnsLogin(String strId, String strToken, String strType) {
		
		String strUrl = MFNetworkManager.BASE_URL + "/user/set_login_sns.php";
		
		Hashtable<String, String> body = new Hashtable<String, String>();
		body.put("id", strId);
		body.put("access_token", strToken);
		body.put("join_type", strType);
		
		MFNetworkManager.getInstance(this).requestPostData(MFNetworkManager.REQUEST_LOGIN, strUrl, body, mNetworkListener);
	}			
	
	private void requestLogin(String strId, String strPassword, boolean AutoLogin) {
		bAutoLogin = AutoLogin;		
		
		String strUrl = MFNetworkManager.BASE_URL + "/user/set_login.php";
		Hashtable<String, String> body = new Hashtable<String, String>();
		body.put("email", strId);
		body.put("passwd", strPassword);
		
		MFNetworkManager.getInstance(this).requestPostData(MFNetworkManager.REQUEST_LOGIN, strUrl, body, mNetworkListener);
	}		
	
	private void showFindIdDialog() {
		new FindIdDialog(mContext, new OnFindIdListener() {
			
			public void onFindPartId(String strName, String strNicName) {
				String strUrl = MFNetworkManager.BASE_URL + "/user/get_idsearch.php";
				strUrl += "?name=" + strName;
				strUrl += "&nickname=" + strNicName;
				MFNetworkManager.getInstance(mContext).requestGetData(MFNetworkManager.REQUEST_FIND_ID, strUrl, mNetworkListener);				
			}
		}).show();
	}
	
	private void showFindPartIdDialog(String strPartId) {
		new FindPartIdDialog(mContext, strPartId, new OnFindPartIdListener() {
			
			public void onFindAllId() {
				showFindAllIdDialog();
			}
		}).show();
	}
	
	private void showFindAllIdDialog() {
		new FindAllIdDialog(mContext, new OnFindAllIdListener() {
			
			@Override
			public void onSendIdEmail(String strNeme, String strNickname, String strEmail) {
				String strUrl = MFNetworkManager.BASE_URL + "/user/set_idsearch.php";

				Hashtable<String, String> body = new Hashtable<String, String>();
				body.put("name", strNeme);
				body.put("nickname", strNickname);
				
				MFNetworkManager.getInstance(mContext).requestPostData(MFNetworkManager.REQUEST_FIND_ALLID, strUrl, body, mNetworkListener);
			}
		}).show();
	}
	
	private void showFindPasswordDialog() {
		new FindPasswordDialog(mContext, new OnFindPasswordListener() {
			
			public void onFindPassword(String strEmail) {
				String strUrl = MFNetworkManager.BASE_URL + "/user/set_passsearch.php";
				
				Hashtable<String, String> body = new Hashtable<String, String>();
				body.put("email", strEmail);
				
				MFNetworkManager.getInstance(mContext).requestPostData(MFNetworkManager.REQUEST_TEMP_PASSWORD, strUrl, body, mNetworkListener);
			}
		}).show();
	}
	
	private void showSendPasswordDialog() {
		new SendPasswordDialog(mContext).show();
	}
	
	IOnNetworkListener mNetworkListener = new IOnNetworkListener() {
		
		@Override
		public void onNetMessage(int resultCode, NetMessage message) {
			try {
	            //서버 여동 데이터
	            if( message instanceof NetJsonData ) {
	                long magicNum = ((NetJsonData) message).getMagicNum();
	                String json = ((NetJsonData) message).getResponseJson();
	                
	                if( json == null ) {
	                    throw new Exception("invalid json data");
	                }
	                
	                Gson gson = new Gson();
	                
	                if (magicNum == MFNetworkManager.REQUEST_LOGIN || 
	                	magicNum == MFNetworkManager.REQUEST_LOGIN_WEIBO || 
	                	magicNum == MFNetworkManager.REQUEST_LOGIN_WECHAT) {
	                	
	                	ResLoginData resultData = (ResLoginData)gson.fromJson(json, ResLoginData.class);
	                    if( resultData == null ) {
	                        throw new Exception("Gson parsing error");
	                    }
	                    
	                    if (resultData.isSuccsess()) {
	                    
	                    	if (magicNum == MFNetworkManager.REQUEST_LOGIN) {
	                    		 mPrf.setMem_idx(bAutoLogin ? resultData.getMem_idx() : "");
		                    }
		                    
		                    MFDataManager.getInstance(getApplicationContext()).setMemberIdx(resultData.getMem_idx());
		                    MFDebug.w("Mem_idx = " + resultData.getMem_idx());
		                    
	                    	Intent intent = new Intent(LoginActivity.this, MainActivity.class);
		            		startActivity(intent);
		            		finish();
	                    } else {
	                    	MFToastUtil.NetResponseToast(getApplicationContext(), resultData.getResultcode(), resultData.getResultmsg());
	                    }
		            	
		            	
	                } else if (magicNum == MFNetworkManager.REQUEST_FIND_ID) {
	                	ResFindIdData resultData = (ResFindIdData)gson.fromJson(json, ResFindIdData.class);
	                	if( resultData == null ) {
	                        throw new Exception("Gson parsing error");
	                    }
	                	
	                	if (resultData.isSuccsess()) {	                		
	                		showFindPartIdDialog(resultData.getId());
	                	} else {
	                		MFToastUtil.NetResponseToast(getApplicationContext(), resultData.getResultcode(), resultData.getResultmsg());
	                	}
	                } else if (magicNum == MFNetworkManager.REQUEST_FIND_ALLID) {
	                	ResDefaultData resultData = (ResDefaultData)gson.fromJson(json, ResDefaultData.class);
	                	if( resultData == null ) {
	                        throw new Exception("Gson parsing error");
	                    }
	                	
	                	if (resultData.isSuccsess()) {
	                	} else {
	                		MFToastUtil.NetResponseToast(getApplicationContext(), resultData.getResultcode(), resultData.getResultmsg());
	                	}
	                } else if (magicNum == MFNetworkManager.REQUEST_TEMP_PASSWORD) {
	                	ResFindIdData resultData = (ResFindIdData)gson.fromJson(json, ResFindIdData.class);
	                	if( resultData == null ) {
	                        throw new Exception("Gson parsing error");
	                    }
	                	
	                	if (resultData.isSuccsess()) {
	                		showSendPasswordDialog();
	                	} else {
	                		MFToastUtil.NetResponseToast(getApplicationContext(), resultData.getResultcode(), resultData.getResultmsg());
	                	}
	                }
	            }	            
	        } catch(Exception e) {	        	
	            MFDebug.e(e);
	        }		
		}
	};		
	
	////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	// weibo
	////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	
	private WeiboAuth mWeiboAuth;
	private Oauth2AccessToken mAccessToken;
	
	public static final String WEIBO_APP_KEY      = "2723328336";
    public static final String WEIBO_REDIRECT_URL = "http://m.wefansapp.com/main/login_weibo.php";
    public static final String WEIBO_SCOPE = "email,direct_messages_read,direct_messages_write,"
            								+ "friendships_groups_read,friendships_groups_write,statuses_to_me_read,"
            								+ "follow_app_official_microblog," + "invitation_write";
    
	private void loginWeibo() {
		mWeiboAuth = new WeiboAuth(this, WEIBO_APP_KEY, WEIBO_REDIRECT_URL, WEIBO_SCOPE);
		mWeiboAuth.anthorize(new AuthListener());
	}	
	
	class AuthListener implements WeiboAuthListener {
        
        @Override
        public void onComplete(Bundle values) {
            // 从 Bundle 中解析 Token
            mAccessToken = Oauth2AccessToken.parseAccessToken(values);
            if (mAccessToken.isSessionValid()) {
                // 显示 Token
                updateTokenView(false);
                
                // 保存 Token 到 SharedPreferences
                AccessTokenKeeper.writeAccessToken(LoginActivity.this, mAccessToken);
                
                requestSnsLogin("", mAccessToken.getToken(), LOGIN_WEIBO);
            } else {
                // 以下几种情况，您会收到 Code：
                // 1. 当您未在平台上注册的应用程序的包名与签名时；
                // 2. 当您注册的应用程序包名与签名不正确时；
                // 3. 当您在平台上注册的包名和签名与您当前测试的应用的包名和签名不匹配时。
                String code = values.getString("code");
                String message = "실패";
                if (!TextUtils.isEmpty(code)) {
                    message = message + "\nObtained the code: " + code;
                }
                Toast.makeText(LoginActivity.this, message, Toast.LENGTH_LONG).show();
            }
        }

        @Override
        public void onCancel() {
            Toast.makeText(LoginActivity.this, 
                    "취소", Toast.LENGTH_LONG).show();
        }

        @Override
        public void onWeiboException(WeiboException e) {
            Toast.makeText(LoginActivity.this, 
                    "Auth exception : " + e.getMessage(), Toast.LENGTH_LONG).show();
        }
    }
	
	private void updateTokenView(boolean hasExisted) {
        String date = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(
                new java.util.Date(mAccessToken.getExpiresTime()));
//        String format = getString(R.string.weibosdk_demo_token_to_string_format_1);
//        mTokenText.setText(String.format(format, mAccessToken.getToken(), date));
//        
//        String message = String.format(format, mAccessToken.getToken(), date);
//        if (hasExisted) {
//            message = getString(R.string.weibosdk_demo_token_has_existed) + "\n" + message;
//        }
//        mTokenText.setText(message);
    }
	
	////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	// wechat
	////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	public static final String WECHAT_APP_ID = "wx2ceb95b3613366b8";
	
	private IWXAPI api;
	
	private void loginWechat() {
		api = WXAPIFactory.createWXAPI(this, WECHAT_APP_ID, false);
		api.registerApp(WECHAT_APP_ID);
	}
}
